package com.toocms.jinjuhang.ui.commodity.classify

import android.app.Application
import android.os.Bundle
import androidx.databinding.*
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ResourceUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.SortType
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.data.goods.GoodsListData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.base.MultiItemViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.binding.viewadapter.recyclerview.LayoutManagers.linear
import com.toocms.tab.binding.viewadapter.recyclerview.LayoutManagers.grid
import com.toocms.tab.binding.viewadapter.recyclerview.LineManagers.horizontal
import com.toocms.tab.binding.viewadapter.recyclerview.LineManagers.both
import com.toocms.tab.bus.event.SingleLiveEvent

class ClassifyCommodityListModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    var p = 1
    val type by lazy {
        bundle?.getString(Constants.BundleKey.KEY_TYPE, Constants.Extra.PRECINCT_TYPE_COMMODITY)
            ?: Constants.Extra.PRECINCT_TYPE_COMMODITY
    }
    val zoneId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ZONE_ID) ?: ""
    }
    var keyword: String? = null
        set(value) {
            field = value
            refresh(false)
        }
    val typeNameObservableField by lazy {
        val typeName = bundle?.getString(Constants.BundleKey.KEY_TITLE) ?: ""
        ObservableField(typeName)
    }

    val getAmountIconObservableField by lazy {
        val content = ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_bottom_gray)
        ObservableField(content)
    }
    val isNewObservableBoolean = ObservableBoolean()
    val sortTypeObservableField = ObservableField<SortType>()
    val layoutManagerFactoryObservableField = ObservableField(linear())
    val isGridManagerObservableBoolean = ObservableBoolean(false)
    val lineManagerFactoryObservableField = ObservableField(horizontal(1))
    val paddingHorizontalObservableFloat = ObservableFloat(0f)
    val paddingTopObservableFloat = ObservableFloat(0f)
    val items = ObservableArrayList<MultiItemViewModel<*>>()
    val itemBinding = ItemBinding.of<MultiItemViewModel<*>> { itemBinding, _, item ->
        when (item.itemType) {
            Constants.RecyclerViewItemType.ITEM_TYPE_ZERO -> itemBinding.set(
                BR.classifyCommodityListLinearItemModel,
                R.layout.item_classify_commodity_linear
            )
            Constants.RecyclerViewItemType.ITEM_TYPE_ONE -> itemBinding.set(
                BR.classifyCommodityListGridItemModel,
                R.layout.item_classify_commodity_grid
            )
        }
    }
    val backClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        finishFragment()
    })
    val getAmountClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortTypeObservableField.get()) {
            SortType.SALES_DOWN -> {
                getAmountIconObservableField.set(ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_blue_bottom_gray))
                sortTypeObservableField.set(SortType.SALES_UP)
            }
            SortType.SALES_UP -> {
                getAmountIconObservableField.set(ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_bottom_gray))
                sortTypeObservableField.set(SortType.SYNTHESIZE)
            }
            else -> {
                getAmountIconObservableField.set(ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_gray_bottom_blue))
                sortTypeObservableField.set(SortType.SALES_DOWN)
            }
        }
        refresh(false)
    })
    val newestClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        isNewObservableBoolean.set(!isNewObservableBoolean.get())
        refresh(false)
    })
    val layoutManagerTypeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        if (isGridManagerObservableBoolean.get()) {
            layoutManagerFactoryObservableField.set(linear())
            isGridManagerObservableBoolean.set(false)
            lineManagerFactoryObservableField.set(horizontal(1))
            paddingHorizontalObservableFloat.set(0f)
            paddingTopObservableFloat.set(0f)
        } else {
            layoutManagerFactoryObservableField.set(grid(2))
            isGridManagerObservableBoolean.set(true)
            lineManagerFactoryObservableField.set(both(15))
            paddingHorizontalObservableFloat.set(ConvertUtils.dp2px(15f).toFloat())
            paddingTopObservableFloat.set(ConvertUtils.dp2px(25f).toFloat())
        }
        items.clear()
        refresh(false)
    })

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh(false)
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })


    init {
        layoutManagerTypeClickBindingCommand.execute()
    }

    private fun refresh(isShowLoading: Boolean) {
        p = 1
        requestData(isShowLoading)
    }

    private fun load() {
        p++
        requestData(false)
    }


    private fun requestData(isShowLoading: Boolean) {
        val params = mutableMapOf<String, String?>()
        params["zone_id"] = zoneId
        params["keywords"] = keyword
        params["is_new"] = if (isNewObservableBoolean.get()) "1" else ""
        params["p"] = p.toString()
        params["sort"] = sortTypeObservableField.get()?.code ?: ""
        val url = when (type) {
            Constants.Extra.PRECINCT_TYPE_COMMODITY -> Urls.Goods.GOODS_LIST
            Constants.Extra.PRECINCT_TYPE_SALVATION -> Urls.Goods.RESCUE_LIST
            else -> Urls.Goods.GOODS_LIST
        }
        requestData(url,
            params,
            resultClass = GoodsListData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (it.zone_name != typeNameObservableField.get()) {
                    typeNameObservableField.set(it.zone_name)
                }
                if (1 == p) items.clear()
                it.list?.forEach { item ->
                    if (isGridManagerObservableBoolean.get()) {
                        items += ClassifyCommodityListGridItemModel(
                            this@ClassifyCommodityListModel,
                            ObservableField(item)
                        )
                    } else {
                        items += ClassifyCommodityListLinearItemModel(
                            this@ClassifyCommodityListModel,
                            ObservableField(item)
                        )
                    }
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }


}